package com.xm.queue;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延迟队列
 *   特点：元素在指定延迟时间后才能被取出。
 *   适用场景：定时任务调度、缓存过期。
 */
public class TestDelayQueue08 {
    public static void main(String[] args) {
        DelayQueue<DelayedTask> delayQueue = new DelayQueue<DelayedTask>();
        delayQueue.offer(new DelayedTask("TaskA", 3000));
        delayQueue.offer(new DelayedTask("TaskB", 1000));

        while (!delayQueue.isEmpty()) {
            try {
                DelayedTask task = delayQueue.take();
                System.out.println("执行任务：" + task.getName());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class DelayedTask implements Delayed {
    private String name;
    private long startTime;// 执行时间（毫秒）

    public DelayedTask(String name, long startTime) {
        this.name = name;
        this.startTime = startTime;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.startTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return Long.compare(this.startTime, ((DelayedTask) o).startTime);
    }

    public String getName() {
        return name;
    }

    public long getStartTime() {
        return startTime;
    }
}
